<template>
  <div class="app-container">
    <h1>工资设置页面</h1>
    <!-- 顶部筛选区域 -->
    <div class="filter-container" style="border: 1px solid #ebeef5; border-radius: 4px; padding: 15px; margin-bottom: 20px;">
      <el-form>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="选择部门">
              <el-select
                v-model="selectedDepartment"
                placeholder="请选择部门"
                @change="handleDepartmentChange"
                style="width: 100%;"
              >
                <el-option
                  v-for="dept in departments"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="选择员工">
              <el-select
                v-model="selectedEmployee"
                placeholder="请选择员工"
                :disabled="!selectedDepartment"
                @change="handleEmployeeSelect"
                style="width: 100%;"
              >
                <el-option
                  v-for="emp in filteredEmployees"
                  :key="emp.id"
                  :label="emp.name"
                  :value="emp.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 模具搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模具编号">
        <el-input v-model="queryParams.moldNo"></el-input>
      </el-form-item>
      <el-form-item label="模具名称">
        <el-input v-model="queryParams.moldName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 模具列表 -->
    <el-tooltip placement="top">
      <div slot="content">点击任意一行列，即可在下方查看单价信息记录</div>
      <el-table
        :data="moldList"
        border
        @row-click="handleRowClick"
        :row-class-name="rowClassName"
      >
        <el-table-column align="center" prop="moldNo" label="模具编号" />
        <el-table-column align="center" prop="moldName" label="模具名称" />
        <el-table-column align="center" prop="standardWeight" label="标准克重" />
        <el-table-column align="center" prop="pieceNum" label="出数" />
      </el-table>
    </el-tooltip>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />

    <!-- 标签页 -->
    <el-tabs v-model="activeName" @tab-click="handleClick" v-if="showCard">
      <!-- 成型计件单价 -->
      <el-tab-pane name="first" label="成型计件单价">
        <el-table
          :data="moldPriceList"
          @row-click="handleMoldPriceRowClick"
          :row-class-name="rowClassNameDetail"
          border
        >
          <el-table-column align="center" prop="material" label="原料" />
          <el-table-column align="center" prop="technique" label="工艺" />
          <el-table-column align="center" prop="mold" label="模穴" />
          <el-table-column align="center" prop="standardPrice" label="标准定额" />
          <el-table-column align="center" prop="standardSalary" label="标准工资" />
          <el-table-column align="center" prop="piecePrice" label="计件单价" />
          <el-table-column align="center" prop="passRate" label="合格率因子" width="120px">
            <template slot-scope="scope">
              <span>{{ scope.row.passRate }}</span>
              <el-tooltip class="item" effect="dark" content="合格率影响实际收入" placement="top">
                <i class="el-icon-question" style="margin-left: 5px;"></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        
        <div style="margin-top: 30px;">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" @click="handleSave">保存</el-button>
            </el-col>
          </el-row>
          
          <el-form :model="moldedPriceForm" ref="moldedPriceForm" label-width="80px" :rules="rules.moldedPrice">
            <el-row>
              <el-col :span="8">
                <el-form-item label="标准定额" prop="standardPrice">
                  <el-input
                    v-model.number="moldedPriceForm.standardPrice"
                    @input="calculatePiecePrice"
                    placeholder="请输入标准定额"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="标准工资" prop="standardSalary">
                  <el-input
                    v-model.number="moldedPriceForm.standardSalary"
                    @input="calculatePiecePrice"
                    placeholder="请输入标准工资"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-show="isPieceworkPosition">
                <el-form-item label="合格率因子" prop="passRate">
                  <el-input
                    v-model.number="moldedPriceForm.passRate"
                    @input="calculatePiecePrice"
                    placeholder="请输入合格率因子（0.1-1）"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="计件单价" prop="piecePrice">
                  <el-input
                    v-model="moldedPriceForm.piecePrice"
                    placeholder="请输入计件单价"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 合格率影响提示 -->
            <el-row v-show="isPieceworkPosition && moldedPriceForm.passRate < 1">
              <el-col :span="24">
                <el-alert
                  title="注意：当前合格率低于100%，实际计件单价将按比例调整"
                  type="warning"
                  center
                  show-icon
                ></el-alert>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 花纸单价 -->
      <el-tab-pane name="second" label="花纸单价">
        <el-form :model="paperPriceForm" ref="paperPriceForm" label-width="80px" :rules="rules.paperPrice">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" @click="handleSave">保存</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="烘花单价" prop="waxPrice">
                <el-input v-model.number="paperPriceForm.waxPrice" placeholder="请输入烘花单价"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="夹花单价" prop="foldPrice">
                <el-input v-model.number="paperPriceForm.foldPrice" placeholder="请输入夹花单价"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="刷花单价" prop="cleanPrice">
                <el-input v-model.number="paperPriceForm.cleanPrice" placeholder="请输入刷花单价"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="订花单价" prop="subscriptionPrice">
                <el-input v-model.number="paperPriceForm.subscriptionPrice" placeholder="请输入订花单价"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="冲花单价" prop="coverPrice">
                <el-input v-model.number="paperPriceForm.coverPrice" placeholder="请输入冲花单价"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="贴花单价" prop="stickerPrice">
                <el-input v-model.number="paperPriceForm.stickerPrice" placeholder="请输入贴花单价"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>

      <!-- 研磨单价 -->
      <el-tab-pane name="third" label="研磨单价">
        <el-form :model="grindPriceForm" ref="grindPriceForm" label-width="80px" :rules="rules.grindPrice">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" @click="handleSave">保存</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="磨边单价" prop="edgePrice">
                <el-input v-model.number="grindPriceForm.edgePrice" placeholder="请输入磨边单价"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="磨孔单价" prop="holePrice">
                <el-input v-model.number="grindPriceForm.holePrice" placeholder="请输入磨孔单价"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="抛光单价" prop="grindingPrice">
                <el-input v-model.number="grindPriceForm.grindingPrice" placeholder="请输入抛光单价"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>

      <!-- 包装单价 -->
      <el-tab-pane name="fourth" label="包装单价">
        <el-form :model="packagePriceForm" ref="packagePriceForm" label-width="80px" :rules="rules.packagePrice">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" @click="handleSave">保存</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="装箱单价" prop="boxPrice">
                <el-input v-model.number="packagePriceForm.boxPrice" placeholder="请输入装箱单价"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="打包单价" prop="packagePrice">
                <el-input v-model.number="packagePriceForm.packagePrice" placeholder="请输入打包单价"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>

      <!-- 质检单价 -->
      <el-tab-pane name="fifth" label="质检单价">
        <el-form :model="qualityPriceForm" ref="qualityPriceForm" label-width="240px" :rules="rules.qualityPrice">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" @click="handleSave">保存</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="每机台质检单价( 0 到 500 )" prop="inspectionPrice">
                <el-input v-model.number="qualityPriceForm.inspectionPrice" placeholder="请输入检验单价"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="每机台质检单价( 500 到 500以上 )" prop="detectionPrice">
                <el-input v-model.number="qualityPriceForm.detectionPrice" placeholder="请输入检测单价"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>

      <!-- 可选因子表 -->
      <el-tab-pane name="sixth" label="可选因子表">
        <el-row style="margin-bottom: 10px;">
          <el-col :span="4">
            <el-input v-model="factorFilter" placeholder="搜索因子名称" />
          </el-col>
          <el-col :span="6">
            <el-select v-model="filterPosition" placeholder="按岗位过滤">
              <el-option label="所有岗位" value="" />
              <el-option v-for="pos in positions" :key="pos" :label="pos" :value="pos" />
            </el-select>
          </el-col>
        </el-row>
        
        <!-- 带复选框的因子表格 -->
        <el-table
          ref="factorTable"
          :data="filteredFactorTableData"
          border
          @row-click="handleFactorRowClick"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column align="center" prop="factorName" label="因子名称" width="180px" />
          <el-table-column align="center" prop="applicablePosition" label="适用岗位" width="120px" />
          <el-table-column align="center" prop="description" label="说明" />
          <el-table-column align="center" prop="exampleRange" label="示例/取值范围" width="200px" />
        </el-table>

        <!-- 应用因子按钮 -->
        <el-row>
          <el-col :span="24">
            <el-button type="primary" @click="applySelectedFactors">
              应用选中因子到工资计算
            </el-button>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 员工工资计算标签页 -->
      <el-tab-pane name="seventh" label="员工工资计算">
        <div class="salary-calculation-container">
          <h3 style="margin: 20px 0 10px;">员工工资计算</h3>
          
          <!-- 已选择的因子显示 -->
          <div v-if="selectedFactors.length > 0" class="selected-factors">
            <h4>已选择的计算因子：</h4>
            <el-tag
              v-for="factor in selectedFactors"
              :key="factor.factorName"
              effect="plain"
              closable
              @close="removeFactor(factor)"
            >
              {{ factor.factorName }} ({{ factor.exampleRange }})
            </el-tag>
          </div>
          
          <!-- 输入表单 -->
          <el-form :model="salaryCalculationForm" label-width="150px">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="员工姓名">
                  <el-input
                    v-model="selectedEmployeeName"
                    placeholder="请选择员工"
                    :disabled="!selectedEmployee"
                    @click="openEmployeeSelectModal"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="所属部门">
                  <el-input v-model="selectedDepartmentName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="岗位类型">
                  <el-input v-model="employeePosition" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" v-show="isPieceworkEmployee">
              <el-col :span="12">
                <el-form-item label="实际完成件数">
                  <el-input
                    v-model.number="salaryCalculationForm.pieceCount"
                    @input="calculateFinalSalary"
                    placeholder="请输入实际完成件数"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合格率因子">
                  <el-input
                    v-model.number="salaryCalculationForm.passRate"
                    @input="calculateFinalSalary"
                    placeholder="请输入合格率因子（0.1-1）"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" v-show="isHourlyEmployee">
              <el-col :span="12">
                <el-form-item label="实际工作小时">
                  <el-input
                    v-model.number="salaryCalculationForm.workHours"
                    @input="calculateFinalSalary"
                    placeholder="请输入实际工作小时"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="小时工资单价">
                  <el-input
                    v-model.number="salaryCalculationForm.hourlyRate"
                    @input="calculateFinalSalary"
                    placeholder="请输入小时工资单价"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" v-show="isManagementEmployee">
              <el-col :span="12">
                <el-form-item label="基本工资">
                  <el-input
                    v-model.number="salaryCalculationForm.baseSalary"
                    @input="calculateFinalSalary"
                    placeholder="请输入基本工资"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="绩效系数">
                  <el-input
                    v-model.number="salaryCalculationForm.performanceRate"
                    @input="calculateFinalSalary"
                    placeholder="请输入绩效系数（0.5-1.5）"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" v-show="selectedEmployee">
              <el-col :span="12">
                <el-form-item label="奖金">
                  <el-input
                    v-model.number="salaryCalculationForm.bonus"
                    @input="calculateFinalSalary"
                    placeholder="请输入奖金金额"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="扣款">
                  <el-input
                    v-model.number="salaryCalculationForm.deduction"
                    @input="calculateFinalSalary"
                    placeholder="请输入扣款金额"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-button type="primary" @click="calculateFinalSalary">计算工资</el-button>
                <el-button style="margin-left: 10px;" @click="resetSalaryForm">重置</el-button>
              </el-col>
            </el-row>
          </el-form>

          <!-- 计算结果 -->
          <div class="result-box" v-if="showResult">
            <h4>计算结果</h4>
            <div class="result-item">
              <span class="label">基础工资：</span>
              <span class="value">{{ baseSalary.toFixed(2) }} 元</span>
            </div>
            <div class="result-item" v-show="adjustment !== 0">
              <span class="label">合格率调整：</span>
              <span class="value" :class="{'text-danger': adjustment < 0}">
                {{ adjustment.toFixed(2) }} 元
              </span>
            </div>
            <div class="result-item" v-show="bonus > 0">
              <span class="label">奖金：</span>
              <span class="value">{{ bonus.toFixed(2) }} 元</span>
            </div>
            <div class="result-item" v-show="deduction > 0">
              <span class="label">扣款：</span>
              <span class="value text-danger">{{ deduction.toFixed(2) }} 元</span>
            </div>
            <div class="result-item" style="font-size: 1.2em; color: #f56c6c;">
              <span class="label">最终工资：</span>
              <span class="value">{{ finalSalary.toFixed(2) }} 元</span>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  name: 'SalarySetting',
  data() {
    return {
      // 部门与员工数据
      departments: [
        { id: 1, name: '成型车间' },
        { id: 2, name: '注塑车间' },
        { id: 3, name: '质检部' },
        { id: 4, name: '包装部' },
        { id: 5, name: '管理部' }
      ],
      allEmployees: [
        { id: 101, name: '张三', departmentId: 1, position: '成型岗位（计件）', passRate: 0.95, baseSalary: 2500, hourlyRate: 20, piecePrice: 58 },
        { id: 102, name: '李四', departmentId: 1, position: '成型岗位（计时）', passRate: 1, baseSalary: 3000, hourlyRate: 25 },
        { id: 201, name: '王五', departmentId: 3, position: '质检岗位', passRate: 1, baseSalary: 3500, hourlyRate: 28 },
        { id: 202, name: '赵六', departmentId: 3, position: '质检岗位', passRate: 1, baseSalary: 3200, hourlyRate: 26 },
        { id: 301, name: '孙七', departmentId: 4, position: '包装岗位', passRate: 1, baseSalary: 2800, hourlyRate: 22 },
        { id: 501, name: '周八', departmentId: 5, position: '管理岗位', passRate: 1, baseSalary: 5000, performanceRate: 1 }
      ],
      selectedDepartment: null,
      selectedEmployee: null,
      selectedEmployeeName: '',
      selectedDepartmentName: '',
      employeePosition: '',
      
      // 页面控制数据
      showSearch: true,
      showCard: false,
      selectedMoldNo: '',
      selectedPriceId: null,
      activeName: 'first',
      
      // 表格数据
      moldList: [
        { pieceNum: 1, moldNo: 'MYL021608', moldName: '圆盘', standardWeight: 13 },
        { pieceNum: 4, moldNo: 'MYL021610', moldName: '碟', standardWeight: 9 },
        { pieceNum: 6, moldNo: 'MYL0229098', moldName: '四方碟', standardWeight: 18 }
      ],
      moldPriceList: [
        { id: 1, material: 'A5', technique: '单色内压花罩光', mold: '2', standardPrice: 1000, standardSalary: 58000, piecePrice: 58, passRate: 0.95 },
        { id: 2, material: 'A1', technique: '单色内压花罩光', mold: '2', standardPrice: 2000, standardSalary: 10000, piecePrice: 5, passRate: 0.9 }
      ],
      
      // 表单数据
      moldedPriceForm: {
        standardPrice: 0,
        standardSalary: 0,
        piecePrice: 0,
        passRate: 1
      },
      paperPriceForm: {
        waxPrice: 0,
        foldPrice: 0,
        cleanPrice: 0,
        subscriptionPrice: 0,
        coverPrice: 0,
        stickerPrice: 0
      },
      grindPriceForm: {
        edgePrice: 0,
        holePrice: 0,
        grindingPrice: 0
      },
      packagePriceForm: {
        boxPrice: 0,
        packagePrice: 0
      },
      qualityPriceForm: {
        inspectionPrice: 0,
        detectionPrice: 0
      },
      
      // 员工工资计算表单
      salaryCalculationForm: {
        pieceCount: 0,
        passRate: 1,
        workHours: 0,
        hourlyRate: 0,
        baseSalary: 0,
        performanceRate: 1,
        bonus: 0,
        deduction: 0
      },
      baseSalary: 0,
      adjustment: 0,
      bonus: 0,
      deduction: 0,
      finalSalary: 0,
      showResult: false,
      
      // 查询参数
      queryParams: { pageNum: 1, pageSize: 10, moldNo: '', moldName: '' },
      total: 0,
      
      // 因子表数据
      positions: ['成型岗位', '花纸岗位', '研磨岗位', '质检岗位', '包装岗位', '管理岗位'],
      factorFilter: '',
      filterPosition: '',
      factorTableData: [
        { factorName: '计时工价', applicablePosition: '所有计时岗位', description: 'hourly rate（元/小时）', exampleRange: '15-30元' },
        { factorName: '保底工资', applicablePosition: '成型、研磨（计件）', description: '月保底收入', exampleRange: '3000-5000元/月' },
        { factorName: '成型计件单价', applicablePosition: '成型岗位（计件）', description: '成型工序单件计价', exampleRange: '0.5-5元/件' },
        { factorName: '花纸单价', applicablePosition: '花纸岗位', description: '花纸装饰单件计价', exampleRange: '0.3-2元/件' },
        { factorName: '质检车数单价', applicablePosition: '质检岗位', description: '每车检验补贴', exampleRange: '10-30元/车' },
        { factorName: '班次倍数', applicablePosition: '成型（计件/计时）', description: '班次工资系数', exampleRange: '第一班1.0，第二班1.2' },
        { factorName: '绩效系数', applicablePosition: '管理岗位', description: '月度绩效调整', exampleRange: '0.5-1.5' }
      ],
      
      // 选中的因子
      selectedFactors: [],
      
      // 表单验证规则
      rules: {
        moldedPrice: {
          standardPrice: [
            { required: true, message: '请输入标准定额', trigger: 'blur' },
            { type: 'number', min: 1, message: '标准定额必须大于0', trigger: 'blur' }
          ],
          standardSalary: [
            { required: true, message: '请输入标准工资', trigger: 'blur' },
            { type: 'number', min: 0, message: '标准工资不能为负数', trigger: 'blur' }
          ],
          passRate: [
            { required: true, message: '请输入合格率因子', trigger: 'blur' },
            { type: 'number', min: 0.1, max: 1, message: '合格率因子范围为0.1-1', trigger: 'blur' }
          ]
        },
        paperPrice: { /* 花纸单价表单验证规则 */ },
        grindPrice: { /* 研磨单价表单验证规则 */ },
        packagePrice: { /* 包装单价表单验证规则 */ },
        qualityPrice: { /* 质检单价表单验证规则 */ }
      }
    };
  },
  computed: {
    // 过滤员工列表
    filteredEmployees() {
      if (!this.selectedDepartment) return [];
      return this.allEmployees.filter(emp => emp.departmentId === this.selectedDepartment);
    },
    // 过滤因子表数据
    filteredFactorTableData() {
      let data = this.factorTableData;
      if (this.filterPosition) data = data.filter(factor => factor.applicablePosition.includes(this.filterPosition));
      if (this.factorFilter) data = data.filter(factor => factor.factorName.includes(this.factorFilter));
      return data;
    },
    // 判断当前选择的是否为计件岗位
    isPieceworkPosition() {
      const employee = this.allEmployees.find(emp => emp.id === this.selectedEmployee);
      return employee?.position.includes('计件');
    },
    // 判断当前选择的是否为计件制员工
    isPieceworkEmployee() {
      return this.employeePosition.includes('计件');
    },
    // 判断当前选择的是否为计时制员工
    isHourlyEmployee() {
      return this.employeePosition.includes('计时');
    },
    // 判断当前选择的是否为管理岗位
    isManagementEmployee() {
      return this.employeePosition.includes('管理');
    }
  },
  methods: {
    // 部门选择变化时
    handleDepartmentChange(departmentId) {
      this.selectedDepartment = departmentId;
      this.selectedEmployee = null; // 清空员工选择
      this.selectedEmployeeName = '';
      this.selectedDepartmentName = '';
      this.employeePosition = '';
      console.log('加载部门', departmentId, '的员工列表');
    },

    // 员工选择事件
    handleEmployeeSelect(employeeId) {
      const employee = this.allEmployees.find(emp => emp.id === employeeId);
      if (employee) {
        this.selectedEmployeeName = employee.name;
        this.selectedDepartmentName = this.departments.find(dept => dept.id === employee.departmentId)?.name || '';
        this.employeePosition = employee.position;
        
        // 初始化工资计算表单
        this.resetSalaryForm();
        
        // 根据岗位类型设置默认值
        if (this.isPieceworkEmployee) {
          this.salaryCalculationForm.passRate = employee.passRate || 1;
        } else if (this.isHourlyEmployee) {
          this.salaryCalculationForm.hourlyRate = employee.hourlyRate || 0;
        } else if (this.isManagementEmployee) {
          this.salaryCalculationForm.baseSalary = employee.baseSalary || 0;
          this.salaryCalculationForm.performanceRate = employee.performanceRate || 1;
        }
        
        this.$message({
          message: `已选择员工：${employee.name}（${employee.position}）`,
          type: 'info'
        });
      }
      // 选择员工后显示标签页
      this.showCard = true;
    },

    // 计算计件单价（包含合格率因子）
    calculatePiecePrice() {
      const standardPrice = Number(this.moldedPriceForm.standardPrice) || 0;
      const standardSalary = Number(this.moldedPriceForm.standardSalary) || 0;
      const passRate = Number(this.moldedPriceForm.passRate) || 1;
      
      if (standardPrice <= 0) {
        this.moldedPriceForm.piecePrice = 0;
        return this.$message.warn('标准定额必须大于0');
      }
      
      // 计件单价 = (标准工资 / 标准定额) × 合格率因子
      this.moldedPriceForm.piecePrice = (standardSalary / standardPrice * passRate).toFixed(2);
    },
    
    // 重置工资计算表单
    resetSalaryForm() {
      this.salaryCalculationForm = {
        pieceCount: 0,
        passRate: 1,
        workHours: 0,
        hourlyRate: 0,
        baseSalary: 0,
        performanceRate: 1,
        bonus: 0,
        deduction: 0
      };
      this.baseSalary = 0;
      this.adjustment = 0;
      this.bonus = 0;
      this.deduction = 0;
      this.finalSalary = 0;
      this.showResult = false;
    },
    
    // 表格行点击事件
    handleRowClick(row) {
      console.log('选中模具:', row);
      this.selectedMoldNo = row.moldNo;
      // 选中模具后显示标签页
      this.showCard = true;
      // 这里可以添加加载模具对应单价数据的逻辑
    },
    
        // 模具单价表格行点击事件
    handleMoldPriceRowClick(row) {
      console.log('选中单价记录:', row);
      this.selectedPriceId = row.id;
      // 填充表单数据
      this.moldedPriceForm = {
        standardPrice: row.standardPrice || 0,
        standardSalary: row.standardSalary || 0,
        piecePrice: row.piecePrice || 0,
        passRate: row.passRate || 1
      };
    },
    
    // 因子表格行点击事件
    handleFactorRowClick(row) {
      console.log('点击因子:', row);
      // 这里可以添加因子行点击逻辑，例如高亮选中状态等
    },
    
    // 处理保存按钮
    handleSave() {
      console.log('保存表单数据');
      this.$message({
        message: '保存成功',
        type: 'success'
      });
    },
    
    // 处理搜索按钮
    handleQuery() {
      console.log('搜索模具:', this.queryParams);
      // 这里可以添加搜索逻辑
    },
    
    // 重置搜索条件
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        moldNo: '',
        moldName: ''
      };
    },
    
    // 分页相关方法
    handleSizeChange(size) {
      this.queryParams.pageSize = size;
      this.handleQuery();
    },
    
    handleCurrentChange(page) {
      this.queryParams.pageNum = page;
      this.handleQuery();
    },
    
    // 标签页点击事件
    handleClick(tab) {
      console.log('切换到标签页:', tab.name);
      // 可以在这里添加标签页切换逻辑
    },
    
    // 表格行样式
    rowClassName({ row, rowIndex }) {
      if (this.selectedMoldNo && row.moldNo === this.selectedMoldNo) {
        return 'highlight-row';
      }
      return '';
    },
    
    // 明细表格行样式
    rowClassNameDetail({ row, rowIndex }) {
      if (this.selectedPriceId && row.id === this.selectedPriceId) {
        return 'highlight-row';
      }
      return '';
    },
    
    // 应用选中的因子到工资计算
    applySelectedFactors() {
      // 通过$refs获取表格选中行
      this.selectedFactors = this.$refs.factorTable.selection;
      
      if (this.selectedFactors.length === 0) {
        return this.$message.warn('请先选择至少一个因子');
      }
      
      // 显示已选择的因子
      const factorNames = this.selectedFactors.map(factor => factor.factorName).join('、');
      this.$message({
        message: `已选择 ${factorNames} 作为工资计算因子`,
        type: 'success'
      });
      
      // 自动切换到工资计算标签页
      this.activeName = 'seventh';
      
      // 应用因子到工资计算表单
      this.applyFactorsToForm();
      
      // 如果已选择员工，立即计算工资
      if (this.selectedEmployee) {
        this.calculateFinalSalary();
      }
    },
    
    // 应用因子到工资计算表单
    applyFactorsToForm() {
      this.selectedFactors.forEach(factor => {
        switch (factor.factorName) {
          case '计时工价':
            if (this.isHourlyEmployee) {
              const rate = parseFloat(factor.exampleRange);
              this.salaryCalculationForm.hourlyRate = rate;
              this.$message({
                message: `已应用「计时工价」因子：${rate}元/小时`,
                type: 'info'
              });
            }
            break;
            
          case '保底工资':
            if (this.isPieceworkEmployee) {
              const guaranteed = parseFloat(factor.exampleRange);
              // 存储保底工资，在计算时使用
              this.salaryCalculationForm.guaranteedSalary = guaranteed;
              this.$message({
                message: `已应用「保底工资」因子：${guaranteed}元/月`,
                type: 'info'
              });
            }
            break;
            
          case '绩效系数':
            if (this.isManagementEmployee) {
              const rate = parseFloat(factor.exampleRange);
              this.salaryCalculationForm.performanceRate = rate;
              this.$message({
                message: `已应用「绩效系数」因子：${rate}`,
                type: 'info'
              });
            }
            break;
            
          case '班次倍数':
            if (this.employeePosition.includes('成型')) {
              const shiftFactor = factor.exampleRange;
              // 班次倍数示例格式："第一班1.0，第二班1.2"
              this.salaryCalculationForm.shiftFactor = shiftFactor;
              this.$message({
                message: `已应用「班次倍数」因子：${shiftFactor}`,
                type: 'info'
              });
            }
            break;
            
          // 其他因子可以在这里添加处理逻辑
        }
      });
    },
    
    // 移除单个因子
    removeFactor(factor) {
      this.selectedFactors = this.selectedFactors.filter(item => item.factorName !== factor.factorName);
      this.$message({
        message: `已移除因子：${factor.factorName}`,
        type: 'info'
      });
      
      // 重新应用剩余因子
      this.applyFactorsToForm();
      
      // 如果已选择员工，重新计算工资
      if (this.selectedEmployee) {
        this.calculateFinalSalary();
      }
    },
    
    // 计算最终工资（核心方法）
    calculateFinalSalary() {
      if (!this.selectedEmployee) {
        return this.$message.error('请先选择员工');
      }
      
      const employee = this.allEmployees.find(emp => emp.id === this.selectedEmployee);
      if (!employee) {
        return this.$message.error('未找到该员工信息');
      }
      
      // 根据岗位类型计算基础工资
      if (this.isPieceworkEmployee) {
        // 计件制员工
        const pieceCount = Number(this.salaryCalculationForm.pieceCount) || 0;
        const passRate = Number(this.salaryCalculationForm.passRate) || 1;
        const piecePrice = employee.piecePrice || 0;
        
        this.baseSalary = pieceCount * piecePrice;
        this.adjustment = this.baseSalary * (passRate - 1);
        
        // 处理保底工资
        if (this.salaryCalculationForm.guaranteedSalary) {
          const guaranteed = Number(this.salaryCalculationForm.guaranteedSalary);
          if (this.baseSalary < guaranteed) {
            this.baseSalary = guaranteed;
            this.adjustment = 0;
            this.$message({
              message: `因保底工资限制，基础工资调整为：${guaranteed}元`,
              type: 'info'
            });
          }
        }
      } else if (this.isHourlyEmployee) {
        // 计时制员工
        const workHours = Number(this.salaryCalculationForm.workHours) || 0;
        const hourlyRate = Number(this.salaryCalculationForm.hourlyRate) || 0;
        
        this.baseSalary = workHours * hourlyRate;
        this.adjustment = 0;
        
        // 处理班次倍数
        if (this.salaryCalculationForm.shiftFactor) {
          const shiftFactor = this.salaryCalculationForm.shiftFactor;
          // 假设班次倍数格式为 "第一班1.0，第二班1.2"
          // 这里简化处理，实际应用中可能需要选择班次
          const factorValue = parseFloat(shiftFactor.split('，')[0].substring(3));
          if (factorValue) {
            this.baseSalary *= factorValue;
            this.$message({
              message: `因班次倍数调整，基础工资计算为：${this.baseSalary.toFixed(2)}元`,
              type: 'info'
            });
          }
        }
      } else if (this.isManagementEmployee) {
        // 管理岗位
        const baseSalary = Number(this.salaryCalculationForm.baseSalary) || 0;
        const performanceRate = Number(this.salaryCalculationForm.performanceRate) || 1;
        
        this.baseSalary = baseSalary * performanceRate;
        this.adjustment = 0;
      }
      
      // 获取奖金和扣款
      this.bonus = Number(this.salaryCalculationForm.bonus) || 0;
      this.deduction = Number(this.salaryCalculationForm.deduction) || 0;
      
      // 计算最终工资
      this.finalSalary = this.baseSalary + this.adjustment + this.bonus - this.deduction;
      
      // 显示结果
      this.showResult = true;
    },
    
    // 打开员工选择模态框（示例方法，实际可能需要实现模态框）
    openEmployeeSelectModal() {
      // 如果没有选择部门，提示先选择部门
      if (!this.selectedDepartment) {
        return this.$message.warn('请先选择部门');
      }
      
      // 这里可以实现打开员工选择模态框的逻辑
      // 本示例中已经通过下拉选择员工，不需要额外模态框
    }
  },
  created() {
    // 页面初始化逻辑
    console.log('页面初始化');
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.highlight-row {
  background-color: #e6f7ff !important;
}

.salary-calculation-container {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
}

.result-box {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  background-color: #fafafa;
}

.result-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.label {
  width: 120px;
  color: #606266;
}

.value {
  font-weight: bold;
  color: #303133;
}

.text-danger {
  color: #f56c6c;
}

.selected-factors {
  margin: 15px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}
</style>